package com.yima.baseproj.module.sys.login;

import cn.hutool.crypto.digest.BCrypt;
import com.yima.baseproj.module.sys.login.model.LoginLoginModel;
import com.yima.baseproj.module.sys.menu.SysMenuService;
import com.yima.baseproj.module.sys.role.SysRoleService;
import com.yima.baseproj.module.sys.user.SysUserEntity;
import com.yima.baseproj.module.sys.user.SysUserService;
import com.yima.baseproj.module.sys.user.model.SysUserStateEnum;
import com.yima.baseproj.security.SecurityUtil;
import com.yima.baseproj.security.model.LoginClientEnum;
import com.yima.baseproj.security.utils.jwt.JwtUtil;
import com.yima.baseproj.security.exception.LoginAuthenticationException;
import com.yima.baseproj.security.model.UserLoginAuthModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysLoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Resource
    private SysUserService sysUserService;

    public String login(LoginLoginModel loginLoginModel){

        //校验用户名
        SysUserEntity sysUserEntity = sysUserService.findByLoginName(loginLoginModel.getUsername());
        if(sysUserEntity == null){
            throw LoginAuthenticationException.USER_NAME_NOT_EXIST;
        }

        if (!sysUserEntity.getPassword().equals(BCrypt.hashpw(loginLoginModel.getPassword(),sysUserEntity.getSalt()))) {
            throw LoginAuthenticationException.PASSWORD_NOT_EXIST;
        }
        if (SysUserStateEnum.JINYONG.isSame(sysUserEntity.getState())) {
            throw LoginAuthenticationException.USER_LOCKED;
        }
        //返回token
        //用户信息
        String token = JwtUtil.createToken(sysUserEntity.getId(), LoginClientEnum.admin.name());
        SecurityUtil.setTokenToRedis(LoginClientEnum.admin.name(),sysUserEntity.getId(), token);
        //设置用户信息
        UserLoginAuthModel authModel = new UserLoginAuthModel();
        authModel.setUserId(sysUserEntity.getId());
        authModel.setClient(LoginClientEnum.admin.name());
        authModel.setRoleList(sysRoleService.selectPermissionByUserId(sysUserEntity.getId()));
        authModel.setPermissionList(sysMenuService.findAllPerByUserId(sysUserEntity.getId()));
        authModel.setUserEntity(sysUserEntity);

        SecurityUtil.setTokenToRedis(LoginClientEnum.admin.name(),sysUserEntity.getId(),authModel);
        return token;
    }
}
